from nicegui import ui
import pandas as pd
import random
from ex4nicegui import rxui, to_ref

# 创建响应式数据源（字典列表格式）
data_ref = deep_ref([])
# df = pd.DataFrame(array, columns=["Column1", "Column2", "Column3"])

# with ui.card().classes("w-64"):
#     # table = ui.table({}).classes("max-h-32")
#     data = {"col1": [1, 2], "col2": [3, 4]}
#     df = pd.DataFrame(data_ref)
#     # table.view.load_pandas_frame(df)
#     ui.aggrid.from_pandas(data).classes("max-h-40")

# # # 创建响应式表格（参数格式修正）
# rxui.aggrid(
#     options={
#         "defaultColDef": {"flex": 1},
#         "columnDefs": [
#             {"headerName": "Name", "field": "name"},
#             {"headerName": "Age", "field": "age"},
#             {"headerName": "Parent", "field": "parent", "hide": True},
#         ],
#         "rowData": data_ref,  # 直接绑定响应式变量
#         "rowSelection": "multiple",
#     }
# ).classes("max-h-40")

grid = ui.aggrid(
    {
        "defaultColDef": {"flex": 1},
        "columnDefs": [
            {"headerName": "Name", "field": "name"},
            {"headerName": "Age", "field": "age"},
            {"headerName": "Parent", "field": "parent", "hide": True},
        ],
        "rowData": data_ref,
        "rowSelection": "multiple",
    }
).classes("max-h-40")


# 更新函数直接操作响应式变量
def update_data():
    new_data = pd.DataFrame(
        [
            {"name": "Alice", "age": random.random(), "parent": "David"},
            {"name": "Bob", "age": random.random(), "parent": "Eve"},
            {"name": "Carol", "age": random.random(), "parent": "Frank"},
        ]
    )
    data_ref.value = df.to_dict("records")
    # data_ref.value = new_data.to_dict("records")  # 转换为字典列表


# 创建操作按钮
ui.button("更新数据", on_click=update_data)

# 启动应用
ui.run(reload=False)
